import yzCommentInput from "components/ui_components/yz_commentInput";
import yzGoodsposter from "components/ui_components/yz_goodsPoster"
let self = null;
export default {
  data() {
    return {
      id: "",
      dataInfo: {},
      content: "",
      like_num: 0,
      read_num: 0,
      is_advs_type: false,
      is_report_enabled: false,
      is_no_copy_url: false,
      is_no_share: false,
      is_no_share_to_friend: false,
      is_liked: false,
      is_link: false,
      title: "",
      codeUrl: "",
      imgList: [],
      showImg: false,
      imgStart: 0,
      menuLists: [],
      //微信要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮
      // 文章评论
      showCommentInput: false,
      commentInputOptions: {},
      replyName: "",
      commentPage: 1,
      commentList: [],
      last_page: 1,
      commenMember: [],
      commentListMore: [],
      keyInd: 0,
      comment_id: 0,
      comment: false,
      commentNum:0,

      isShowCode: true, //门店营销不显示
      //海报开关
      show_poster:false,
      showShare: false,//分享弹窗
      shareSheetOptions: [],//分享弹窗选项
      // 海报弹窗显示
      posterShow:false,
      posterImg:'',

      diymoney: '',//自定义输入的金额
      diy_money_index: null,
      diy_amount: [5,10, 20, 50, 100],
      showDonate: false
    };
  },
  beforeRouteLeave(to, from, next) {
    // 注意：从商品详情页跳转到商品详情页不触发，to、from不变
    if (self.showImg) {
      self.showImg = false;
      next(false);
    } else {
      next();
    }
  },
  activated() {
    self = this;
    this.id = this.$route.params.id;
    this.codeUrl = "";
    this.menuLists = [];
    this.imgList = [];
    this.showImg = false;
    this.imgStart = 0;
    //获取数据
    this.getData();
    if(this.$route.query.task_type == 'article'){
      this.shareArticleTask();
    }
  },
  mounted() {
    this.dataInfo = {};
    this.title = "";
  },

  methods: {
    toUrl(name, params = {}, query = {}) {
      this.$router.push(this.fun.getUrl(name, params, query));
    },
    openShare() {
      this.shareSheetOptions = [];
      let imgPath = this.$store.state.imgPath;
      if(this.show_poster) {
        this.shareSheetOptions.push({ name: "分享海报", icon: "poster" });
      }
      if (this.fun.isXueXiApp()) {
        this.shareSheetOptions.push({ name: "学习强国", icon: imgPath + "point-hsjz/xuexi-icon.png" });
      }
      this.showShare = true;
    },
    onSelectShareSheet(event) {
      switch (event.name) {
      case "分享海报":
        this.showPost();
        break;
      case "学习强国":
        this.shareApp();
        break;
      }
    },
    async showPost(){
      let { result, msg, data } = await $http.get('plugin.article.api.article.get-poster', {article_id:this.id},'');
      if(!result) return this.$toast(msg);
      this.posterShow = true;
      this.posterImg = data.poster;
    },
    async shareApp(){
      let { title, link, imgUrl, description } = this.shareInfo;
      await this.fun.shareXueXiContent("", link, title, description, imgUrl);
    },
    async shareArticleTask(){
      let json = {
        record_id:this.$route.query.taskID,
        task_type:'article',
        day:this.$route.query.taskDay,
        task_record_id:this.id
      }
      let { result, msg, data } = await $http.get('plugin.task-package.frontend.daily-record.finish-task', json,'');
      if (result == 0) return console.log(msg);
    },
    getQrCode() {
      $http.get("member.member.getArticleQr", {}, "").then(
        response => {
          if (response.result === 1) {
            this.codeUrl = response.data;
          } else {
            this.codeUrl = false;
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    //获取数据
    getData() {
      let that = this;
      let share_uid = this.fun.getKey("share_uid");
      share_uid = this.fun.isTextEmpty(share_uid) ? "" : share_uid;
      let json = { article_id: this.id, share_uid: share_uid };
      let _url = 'plugin.article.api.article.get-article';
      $http.get(_url, json, "").then(
        (response)=> {
          if (response.result == 1) {
            that.title = response.data.title;
            if(response.data.comment){
              that.comment = response.data.comment;
              that.getComment();
            }

            that.dataInfo = response.data;
            that.content = response.data.content;
            that.is_advs_type = response.data.advs_type == 0 ? false : true;
            that.is_report_enabled = response.data.report_enabled == 0 ? false : true;

            that.is_no_copy_url = response.data.no_copy_url == 1 ? true : false; //禁止复制链接
            that.is_no_share = response.data.no_share == 1 ? true : false; //禁止分享至朋友圈
            that.is_no_share_to_friend = response.data.no_share_to_friend == 1 ? true : false; //禁止分享给好友

            that.is_liked = response.data.liked == 0 ? false : true;
            that.is_link = !that.fun.isTextEmpty(response.data.link);
            that.like_num = response.data.like_num + response.data.virtual_like_num;
            that.read_num = response.data.read_num + response.data.virtual_read_num;
            that.show_poster = response.data.show_poster == 1?true:false;
            if (that.is_no_copy_url) {
              that.menuLists.push("menuItem:copyUrl");
            }
            if (that.is_no_share) {
              that.menuLists.push("menuItem:share:timeline");
            }
            if (that.is_no_share_to_friend) {
              that.menuLists.push("menuItem:share:appMessage");
            }
            let wxShareUrl = this.fun.getSiteRoot() + "/addons/yun_shop/?menu#/articleContent/"+ this.id +"?i=" + this.fun.getKeyByI();
            if(this.$route.query.taskID){
              wxShareUrl += `&taskID=${this.$route.query.taskID}&taskDay=${this.$route.query.taskDay}&task_type=article`;
            }
            if(this.dataInfo.has_one_store || (this.dataInfo.detail_page_login_validator == '0')){
              this.isShowCode = false;
            } else {
              this.getQrCode();
            }
            this.shareInfo = {
              title: that.fun.isTextEmpty(that.dataInfo.title) ? "" : that.dataInfo.title,
              link:wxShareUrl,
              imgUrl: that.fun.isTextEmpty(that.dataInfo.thumb) ? "" : that.dataInfo.thumb,
              description: that.fun.isTextEmpty(that.dataInfo.desc) ? "" : that.dataInfo.desc,
              hideMenu: that.menuLists
            };
            that.fun.wxShare(
              "",
              { mid: that.fun.getKeyByMid() },
              this.shareInfo
            );
            that.fun.setWXTitle(that.dataInfo.title || "详情");
            that.imgList = that.getImgSrc(response.data.content);
            this.$nextTick(() => {
              this.insertPosterAttribute();
            });
          } else {
            if (response.msg == "您尚未购买该文章内容,无法观看") {
              that.$dialog.alert({ message: response.msg }).then(()=>{
                that.$router.replace(that.fun.getUrl("payList", { id: that.id }));
              });
            } else {
              that.$dialog
                .alert({ message: response.msg })
                .then(() => {
                  if(that.$route.params.isgood){
                    this.$router.go(-1)
                  }else{
                    that.$router.push(that.fun.getUrl("notice"));
                  }
                })
                .catch(() => {});
            }
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    insertPosterAttribute() {
      const videoTags = document.querySelectorAll('video');
      videoTags.forEach(video => {
        const src = video.getAttribute('src');
        if (src.includes('aliyuncs')) {
          const posterSrc = src + '?x-oss-process=video/snapshot,t_1,m_fast';
          video.setAttribute('poster', posterSrc);
        }
      });
    },
    handleHtml($event) {
      setTimeout(() => {
        console.log($event);
        let that = this;
        if ($event.target) {
          if ($event.target.nodeName == "IMG" && $event.target.parentElement.nodeName !== "A") {
            for (let i = 0; i < that.imgList.length; i++) {
              // 编程式
              if ($event.target.currentSrc.indexOf(that.imgList[i]) > -1) {
                that.imgStart = i;
                that.showImg = true;
                return;
              }
            }
          }
        }
      }, 100);
    },
    getImgSrc(richtext) {
      let imgList = [];
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
        imgList.push(capture);
      });
      return imgList;
    },
    //查看营销
    toAdvs() {
      if (!this.fun.isTextEmpty(this.dataInfo) && this.fun.isTextEmpty(this.dataInfo.advs_link)) {
        return;
      }
      window.location.href = this.fun.funHrefFilters(this.dataInfo.advs_link);
    },

    //点赞
    like(like_num) {
      let json = { article_id: this.id };

      $http.get("plugin.article.api.article.like", json, "").then(
        (response)=> {
          if (response.result === 1) {
            if (response.data.liked == 1) {
              this.is_liked = true;
              this.like_num = like_num + 1;
              this.$toast("点赞成功");
            } else {
              this.is_liked = false;
              this.like_num = like_num - 1;
              if (this.like_num < 0) {
                this.like_num = 0;
              }
              this.$toast("取消点赞");
            }
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },

    //举报
    report() {
      this.$router.push(this.fun.getUrl("noticeReport", { id: this.id }));
    },

    //阅读原文
    link() {
      window.location.href = this.fun.funHrefFilters(this.dataInfo.link);
    },
    //  -----------------------  文章评论 ---------------
    getComment() {
      $http
        .post(
          "plugin.article.api.comment.comment-list",
          {
            page: this.commentPage,
            article_id: this.id
          },
          ""
        )
        .then(response => {
          if (response.result == 1) {
            this.commentList = response.data.list.data;
            for (let i = 0; i < this.commentList.length; i++) {
              if (this.commentList[i].reply_num > 0) {
                this.$set(this.commentList[i], "commentShow", true);
              } else {
                this.$set(this.commentList[i], "commentShow", false);
              }
              this.$set(this.commentList[i], "commenMorePage", "1");
            }
            this.last_page = response.data.list.last_page;
            this.commenMember = response.data.member;
            this.commentNum = response.data.num;
          } else {
            this.$toast(response.msg);
          }
        });
    },
    watchImg(item){
      this.imgList = item;
      this.showImg = true;
    },
    getMore() {
      this.commentPage = this.commentPage + 1;
      $http
        .post(
          "plugin.article.api.comment.comment-list",
          {
            page: this.commentPage,
            article_id: this.id
          },
          ""
        )
        .then(response => {
          if (response.result == 1) {
            let dataMore = response.data.list.data;
            this.commentList = this.commentList.concat(dataMore);
            for (let i = 0; i < this.commentList.length; i++) {
              if (this.commentList[i].reply_num > 0) {
                this.$set(this.commentList[i], "commentShow", true);
              } else {
                this.$set(this.commentList[i], "commentShow", false);
              }
              this.$set(this.commentList[i], "commenMorePage", 1);
            }
            console.log(this.commentList);
            this.last_page = response.data.list.last_page;
          } else {
            this.$toast(response.msg);
          }
        });
    },
    // 加载子评论
    moreCommentLis(id, ind) {
      let url = "plugin.article.api.comment.get-replys";
      // 当前主评论的加载页数 is_page
      let is_page = Number(this.commentList[ind].commenMorePage);
      let dataJson = {
        page: is_page,
        comment_id: id
      };
      $http.post(url, dataJson, "").then(response => {
        if (response.result == 1) {
          let child = response.data.data;
          if (is_page >= 1 && this.commentList[ind].child) {
            child = this.commentList[ind].child.concat(child);
          }
          this.$set(this.commentList[ind], "child", child);
          let mun = this.commentList[ind].reply_num - response.data.data.length;
          this.$set(this.commentList[ind], "reply_num", mun);
          let moreLast_page = response.data.last_page;
          if (is_page >= moreLast_page) {
            is_page = 1;
          } else {
            is_page = is_page + 1;
          }
          this.$set(this.commentList[ind], "commenMorePage", is_page);
        } else {
          this.$toast(response.msg);
        }
      });
    },
    // 发送
    subMainBtn(e) {
      if (e) {
        this.showCommentInput = false;
        this.getReplyComments(e);
      }
    },
    // 发送请求
    getReplyComments(e) {
      let that = this;
      let url;
      let dataJson = {
        images: JSON.stringify(e.imgs),
        content: e.text
      };
      console.log("e.options.type", e.options.type);
      // main 是创建评论  reply 是回复评论
      if (e.options.type == "reply") {
        url = "plugin.article.api.comment.reply-comment";
        dataJson.comment_id = that.replyId;
      } else if (e.options.type == "main") {
        url = "plugin.article.api.comment.create-comment";
        dataJson.article_id = that.id;
      }
      $http.post(url, dataJson,'').then(response => {
        if (response.result == 1) {
          if (e.options.type == "main") {
            that.commentPage = 1;
            that.getComment();
          } else {
            that.updateInfo("getReply", response.data, that.keyInd);
          }
          this.$toast(response.msg);
          console.log(response.data);
        } else {
          this.$toast(response.msg);
        }
      });
    },
    // 回复后更新数据
    updateInfo(key, data, ind) {
      let arr = [];
      arr.push(data);
      if (this.commentList[ind].child) {
        this.commentList[ind].child.unshift(arr[0]);
      } else {
        this.$set(this.commentList[ind], "child", arr);
      }
    },
    subMainCommentBtn() {
      console.log(" main 是创建评论");
      this.showCommentInput = true;
      this.commentInputOptions = {
        type: "main",
        route:"articleContent"
      };
    },
    replyBtn(name, item, ind) {
      this.keyInd = ind;
      this.replyId = "";
      // 回复别人的评论
      this.replyId = item.id;
      this.comment_id = item.comment_id == 0 ? item.comment_id : item.id;
      this.replyName = name;
      this.showCommentInput = true;
      this.commentInputOptions = {
        type: "reply",
        placeholder: "请输入你的回复吧",
        route:"articleContent",
        replyName:this.replyName
      };
      this.commentManagement = false;
    },
    delComment(item, ind, index, key) {
      let id;
      let myUid = window.localStorage.uid;
      id = item.id;
      if (key == "child") {
        console.log(item, "子组件");
        if(item.uid == myUid){
          console.log('可以删除 子评论');
          this.delRequst(id,ind,index,key);
        }
      } else {
        if (item.uid == myUid) {
          console.log('可以删除 主评论');
          this.delRequst(id,ind,index,key);
        }
      }

    },
    delRequst(id,ind,index,key) {
      this.$dialog
        .confirm({ message: "是否删除评论?" })
        .then(() => {
          $http
            .post("plugin.article.api.comment.del", {
              comment_id: id
            },'')
            .then(response => {
              if (response.result == 1) {
                if (key == 'child') {
                  this.commentList[ind].child.splice(index, 1);
                  this.$set(this.commentList[ind], "child", this.commentList[ind].child);
                } else {
                  this.commentList.splice(ind, 1);
                }
                this.$toast(response.data);
              } else {
                this.$toast(response.msg);
              }
            });
        })
        .catch(() => {});
    },
    selectDiyNum(num){
      this.diy_money_index = num;
      this.diymoney = '';
      this.money = this.diy_amount[num];
    },
    async subDonate() {
      if(this.clickLock) return;
      if(this.diymoney) this.money = this.diymoney;
      if(!this.money){
        this.$toast('请选择捐赠的数量');
        return;
      }
      this.clickLock = true;
      let { result, msg, data } = await $http.get('plugin.article-donate-point.frontend.controllers.donate.donate',{
        article_id: this.id,
        donate_num: this.money
      },".");
      this.$toast(msg);
      this.diy_money_index = null;
      this.diymoney = '';
      this.showDonate = false;
      this.clickLock = false;
    }
  },
  components: { yzCommentInput, yzGoodsposter }
};
